package com.lottoad.android.activity.notify;

import java.util.ArrayList;

import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.content.Context;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.lottoad.android.R;
import com.lottoad.android.activity.notify.adapter.LottoAdNotifyAdapter;
import com.lottoad.android.common.BaseActivity;
import com.lottoad.android.cronos.data.CNLottoAdNotifyData;
import com.lottoad.android.cronos.datahandler.CNBaseDataParser;
import com.lottoad.android.cronos.datahandler.CNBaseDataSet;
import com.lottoad.android.cronos.datahandler.CNResultSet;
import com.lottoad.android.cronos.http.CNLottoAdApiSetEx;
import com.lottoad.android.cronos.parser.CNNotifyListParser;
import com.lottoad.android.util.ApplicationUtils;
import com.lottoad.android.util.CNCronosLog;
/**
 * 공지사항 - 공지사항 Activity
 * @author Administrator
 *
 */
public class LottoAdNotifyActivity extends BaseActivity{
	private Context mContext;
	
	/**공지사항 목록 ListView**/
	private ListView mListView;
	private TextView mListEmpty;
	
	/** 요청 페이지 Number **/
	private int mPageNum = 1;
	/** 데이터 셋 유/무 체크 플래그 **/
	private boolean isDataSet = false;
	/** 다음페이지 유/무 체크 플래그 **/
	private boolean isNextPage = false;
	/** 비동기 작업수행 여부 체크 플래그 **/
	private boolean mNetAsyncing = false;
	/** 리스트의 마지막 포지션값 **/
	private int mListLastPosition = 0;
	
	/**공지사항 목록 List Adapter**/
	private LottoAdNotifyAdapter mListAdapter;
	/**공지사항 목록 List DataSetList**/
	private ArrayList<CNBaseDataSet> mDataSetList = new ArrayList<CNBaseDataSet>();
	
	@Override
	protected int onGetContentViewResource() {
		return R.layout.lottoad_menu_notify_list;
	}

	@Override
	protected void onInit() {
		this.mContext = this;
		
		mListView = (ListView) findViewById(R.id.list_view);
		mListEmpty = (TextView) findViewById(R.id.list_empty);
		
		mListAdapter = new LottoAdNotifyAdapter(mContext);
		mListAdapter.setDataSetList(mDataSetList);
		mListView.setAdapter(mListAdapter);
		
		mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				mListAdapter.setSelectedPosition(position);
			}
		});
		
		mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView abslistview, int i) {
				try
		        { 
					if(isDataSet)
					{
						int mLastPosition = abslistview.getLastVisiblePosition();
						CNCronosLog.d("mLastPosition : "+ mLastPosition);
						if((mLastPosition == mListLastPosition - 1) && isNextPage && !mNetAsyncing){ 
							mPageNum = mPageNum + 1;
			            	mNetAsyncing = true;
			            	onRequestData();
			            }
					}
		        }catch(Exception e){ 
		        	
		        }
			}
			
			@Override
			public void onScroll(AbsListView abslistview, int i, int j, int k) {
				
			}
		});
		
		onRequestData();
	}
	
	/**
	 * 공지사항 목록 파싱
	 * @param xmlObject
	 * @throws Exception
	 */
	private void parseNotifyList(Element xmlObject) throws Exception
	{
		
		String Tag = "parseNotifyList";
		
		CNBaseDataParser parser = new CNNotifyListParser();
		CNResultSet resultSet = parser.parse(xmlObject);
		ArrayList<CNBaseDataSet> dataSet = null;
		
		if (resultSet != null)
		{
			dataSet = resultSet.getDataSetList();
			if (dataSet != null)
			{
				int count = dataSet.size();		
				CNCronosLog.d(Tag, "DataSet.size():" + count);
				for (int i = 0; i < count; i++)
				{
					CNLottoAdNotifyData data = (CNLottoAdNotifyData) dataSet.get(i);
					
					System.out.print("============ " + i + " ============");
					System.out.print( "notifyTitle:" + data.notifyTitle);
					System.out.print("notifyContents:" + data.notifyContents);
					System.out.print("notifyDate:" + data.notifyDate);
					
					mDataSetList.add(data);
				}
			}
			
			isNextPage = mDataSetList.size() < resultSet.getTotalCount();
			isDataSet = mDataSetList.size() > 0;
			mListLastPosition =  mDataSetList.size();
		}
		
		mNetAsyncing = false;
		mListAdapter.notifyDataSetChanged();
		
		updateUI();
	}
	
	private void updateUI(){
		if(mDataSetList != null && mDataSetList.size() > 0){
			mListView.setVisibility(View.VISIBLE);
			mListEmpty.setVisibility(View.GONE);
		} else {
			mListView.setVisibility(View.GONE);
			mListEmpty.setVisibility(View.VISIBLE);
		}
	}
	
	@Override
	public String onGetAsyncRequestUrl() {
		CNCronosLog.d("onGetAsyncRequestUrl()");
		String url = null;
		
		CNLottoAdApiSetEx MnetGlobalApiSetEx = CNLottoAdApiSetEx.getInstance();
		url = MnetGlobalApiSetEx.getNotifyListUrl(mContext, mPageNum, 10);
		Log.d("BenTag", "공지사항 url : " + url);
		CNCronosLog.d("onGetAsyncRequestUrl", "url : "+url);
		
		return url;
	}
	
	@Override
	public void onAsyncCancelRequest() 
	{
		super.hideLoadingDialog();
		CNCronosLog.d("onAsyncCancelRequest()");
	}

	@Override
	public void onAsyncDataError(Element xmlObject, String errorMessage)
	{
		super.hideLoadingDialog();
		
		NodeList rcodeNode = xmlObject.getElementsByTagName("rcode");
		String rcode = rcodeNode.item(0).getFirstChild().getNodeValue();
		
		if(!"RET0002".equals(rcode)){
			ApplicationUtils.showOkDialog(mContext, 0, getString(R.string.popup_alert), errorMessage);
		} else {
			updateUI();
		}
	}
	
	@Override
	public void onAsyncPreRequest()
	{
		super.showLoadingDialog();
	}

	@Override
	public void onAsyncRequestCompleted(Element xmlObject)
	{
		super.hideLoadingDialog();
			
		try {
			parseNotifyList(xmlObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onAsyncRequestError(int errorNumber) {
		super.hideLoadingDialog();
		
		ApplicationUtils.showOkDialog(mContext,0,getString(R.string.popup_alert), ApplicationUtils.getErrorMessage(mContext, errorNumber));
	}
}
